package com.xiaoming;

import com.xiaoming.utils.HttpProtocolUtil;
import com.xiaoming.utils.StaticResourceUtil;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;

/***
 * 根据OutputStream封装
 * 需要提供返回方法
 */
@Data
@NoArgsConstructor
public class Response {
    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    // 根据路径获取静态资源
    public void outputHtml(String url) throws IOException, URISyntaxException {
        // 获取静态资源路径
        String resourcePath = StaticResourceUtil.getAbsolutePath(url);
        // 文件存在输出
        File file = new File(resourcePath);
        if (file.exists() && file.isFile()) {
            // 输出
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }

    // 输出
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }
}
